<template>
  <div class="page-container">
    <!--面包屑-->
    <div class="breadcrumb">
      <el-breadcrumb separator-class="el-icon-arrow-right">
        <el-breadcrumb-item>会员中心</el-breadcrumb-item>
        <el-breadcrumb-item>会员管理</el-breadcrumb-item>
        <el-breadcrumb-item>自定义标签管理</el-breadcrumb-item>
      </el-breadcrumb>
    </div>
    <!--工具栏-->
    <div class="toolbar">
      <el-form :inline="true" :model="filters" :size="size"  ref="filters" >
        <el-row class="search-input">
          <el-row class="times mr30">
            <el-form-item label="创建时间：" prop="startTime">
              <el-date-picker
                v-model="filters.startTime"
                type="datetime"
                placeholder="开始时间"
                format="yyyy-MM-dd HH:mm:ss"
                value-format="yyyy-MM-dd HH:mm:ss"
                clearable
                @change="changeStartDate"
                :picker-options="startDateDisabled"
              ></el-date-picker>
            </el-form-item>
            <span class="times-to">-</span>
            <el-form-item prop="endTime">
              <el-date-picker
                v-model="filters.endTime"
                type="datetime"
                placeholder="结束时间"
                format="yyyy-MM-dd HH:mm:ss"
                value-format="yyyy-MM-dd HH:mm:ss"
                clearable
                @change="changeEndDate"
                :picker-options="endDateDisabled"
              ></el-date-picker>
            </el-form-item>

            <el-form-item label="标签名称：" prop="ruleNum">
             <el-input
                v-model.trim="filters.labelName"
                placeholder="输入标签名称"
                maxlength="80"
                clearable
              ></el-input>
           </el-form-item>

            <el-form-item label="所属组织">
            <tree-select
              :options="deptOption"
              placeholder="所属组织"
              v-model="filters.deptId"
              :normalizer="normalizer"
              @select="treeSelect"
              style="width:230px"/>
          </el-form-item>
          </el-row>


          <!-- <el-form-item label="所属组织">
            <tree-select
              :options="deptOption"
              placeholder="所属组织"
              v-model="filters.id"
              :normalizer="normalizer"
              @select="treeSelect"
              style="width:230px"/>
          </el-form-item> -->
        <!-- -->
         <!-- <el-row class="times mr30">
           <el-form-item label="标签名称：" prop="ruleNum">
             <el-input
                v-model.trim="filters.labelName"
                placeholder="输入标签名称"
                maxlength="80"
                clearable
              ></el-input>
           </el-form-item>
         </el-row> -->



        </el-row>
        <el-row class="search-button-noborder">
          <el-form-item>
            <kt-button :plain="true" :label="'重置'" type="primary" @click="resetForm('filters')" />
          </el-form-item>
          <el-form-item>
            <kt-button icon="el-icon-search" :label="'搜索'" type="primary" @click="findPageClick(null)" />
          </el-form-item>
          <el-form-item>
            <kt-button :label="'添加'" type="primary" @click="handleAdd"/>
          </el-form-item>
        </el-row>
      </el-form>
    </div>
          <el-table
            :data="tableList"
            :header-cell-style="{ 'color': '#FFF','background-color': '#409EFF','text-align': 'center'}"
            :highlight-current-row="true"
            :max-height="15000"
            :size="'mini'"
            style="width: 100%"
            class="specialTable"
            :border="false"
            v-loading="loading"
          >
            <el-table-column align="center" label="ID"  element-loading-text>
              <template slot-scope="scope">
                <span>{{ scope.row.id}}</span>
              </template>
            </el-table-column>
            <el-table-column align="center" label="标签名称"  element-loading-text>
              <template slot-scope="scope">
                <span>{{ scope.row.labelName || '-'}}</span>
              </template>
            </el-table-column>
            <el-table-column align="center" label="所属组织"  element-loading-text>
              <template slot-scope="scope">
                <span>{{ scope.row.deptName || '-'}}</span>
              </template>
            </el-table-column>

            <el-table-column align="center" label="创建时间"  element-loading-text>
              <template slot-scope="scope">
                <span>{{ scope.row.createTime || '-'}}</span>
              </template>
            </el-table-column>
            <el-table-column align="center" label="标记次数"  element-loading-text>
              <template slot-scope="scope">
                <span>{{ scope.row.markTimes || '-'}}</span>
              </template>
            </el-table-column>
            <el-table-column class-name="status-col" align="left" fixed="right" label="操作"  width="450">
              <template slot-scope="scope">
                <kt-button
                  @click="handleEdit(scope.row)" type="text" size="mini"  label="编辑" >
                </kt-button>
                 <kt-button
                  @click="handleDeleteInfos(scope.row)" type="text" size="mini"  label="删除" >
                </kt-button>
                <kt-button
                  @click="handleLookInfo(scope.row)" type="text" size="mini"  label="查看" >
                </kt-button>
              </template>
            </el-table-column>
          </el-table>
          <!--分页栏-->
          <div class="toolbar" style="padding:10px;">
            <el-pagination
              layout="total, sizes, prev, pager, next, jumper"
              @current-change="currentChange"
              :current-page="filters.start"
              :page-size="filters.limit"
              :total="totalSize"
              style="float:right;"
              :page-sizes="[10, 20, 30, 40]"
              @size-change="sizeChange"
            ></el-pagination>
          </div>


    <!--新增编辑界面-->
    <el-dialog :title="operation?'添加标签':'查看标签'" :visible.sync="dialogVisible" :close-on-click-modal="false"  @closed="handleClose" class="el-dialog-style">
      <el-form :model="dataForm" :rules="dataFormRules"  ref="dataForm" :size="size" label-position="right">
         <el-form-item class="mb30" v-if="!operation">
           <span class="color333 font16 turnInlineBlock w90 t_r">所属组织：</span>
           <span class="color333 font16">{{dataForm.deptName}}</span>
         </el-form-item>
        <el-form-item  label="标签名称：" prop="labelName">
          <el-input v-model="dataForm.labelName"  auto-complete="off" placeholder="标签名称" style="width:200px" maxlength="20" clearable></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button :size="size"  @click.native="dialogVisible = false"  type="primary" plain>{{$t('action.cancel')}}</el-button>
        <el-button  :size="size" type="primary"  @click.native="submitForm" :loading="editLoading">确定</el-button>
      </div>
    </el-dialog>
    <!--查看界面-->
    <el-dialog :title="'查看标签'" :visible.sync="dialogVisibleLook" :close-on-click-modal="false" class="el-dialog-style">
      <el-form :model="dataFormLook" :rules="dataFormRules"  ref="dataFormLook" :size="size" label-position="right">
         <el-form-item class="mb30">
           <span class="color333 font16 turnInlineBlock w90 t_r">所属组织：</span>
           <span class="color333 font16">{{dataFormLook.deptName}}</span>
         </el-form-item>
        <el-form-item   prop="labelName">
          <span class="color333 font16 turnInlineBlock w90 t_r">标签名称：</span>
          <span class="color333 font16">{{dataFormLook.labelName}}</span>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button :size="size"  @click.native="dialogVisibleLook = false"  type="primary" plain>确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import '@riophae/vue-treeselect/dist/vue-treeselect.css'
  import TreeSelect from '@riophae/vue-treeselect'
  import PopupTreeInput from "@/components/PopupTreeInput";
  import CyTable from "@/views/Core/JicTable";
  import KtButton from "@/views/Core/KtButton";
  import TableColumnFilterDialog from "@/views/Core/TableColumnFilterDialog";
  import { format } from "@/utils/datetime";
  export default {
    components: {
      PopupTreeInput,
      TreeSelect,
      CyTable,
      KtButton,
      TableColumnFilterDialog
    },
    data() {

      return {
        startDateDisabled: {},//开始时间限制
        endDateDisabled: {},//结束时间限制
        loading:true,
        tableList:[],
        checkButton:true,
        deptOption:[],
        operation:true,
        deptName:JSON.parse(localStorage.getItem('user')).deptName,//当前登录组织信息
        deptMsg:localStorage.getItem('user'),//当前登录组织信息
        deptType:localStorage.getItem("deptType"),//当前登录用户所属组织类型
        imgUrl: "",
        growthRuleShow: false, //规则创建成功弹窗
        addDeptOperate: true,
        editDeptOperate: false,
        totalSize: 0,
        size: "small",
        filters: {
          start:1,
          limit:10,
          type:0,
          endTime: null,
          startTime: null,
          labelName:null,
          deptId:localStorage.getItem("deptId"),
        },
        columns: [],
        filterColumns: [],
        pageRequest: { pageNum: 1, pageSize: 10 },
        pageResult: [],
        options: {},
        dialogVisible: false, // 新增编辑界面是否显示
        editLoading: false,
        dialogVisibleLook:false,
        dataFormRules: {
          labelName: [
            { required: true, message: "请输入标签名称", trigger: "blur" }
          ]
        },
        // 新增编辑界面数据
        dataForm: {
          id: null,
          labelName:'',
          deptName:'',
        },
        dataFormLook:{
          labelName:'',
          deptName:'',
        }
      };
    },
    methods: {
    changeStartDate: function() {
      var this_ = this;
      this_.endDateDisabled = {
        disabledDate: time => {
          if (this_.filters.startTime) {
            return time.getTime() <= new Date(this_.filters.startTime).getTime();
          }
        }
      };
    },
    changeEndDate: function() {
      var this_ = this;
      this_.startDateDisabled = {
        disabledDate: time => {
          if (this_.filters.endTime) {
            return time.getTime() >= new Date(this_.filters.endTime).getTime();
          }
        }
      };
    },
       //点击搜索，页码重置
      findPageClick(){
        console.log('下拉框内容：' + this.filters.id)
        this.pageRequest.pageNum = 1;
        this.findPage();
      },
      //所属组织 清楚选择后
      deselect() {
        if (this.filters.deptId == undefined || this.filters.deptId == null) {
            this.queryDeptTree();
        }
      },
      // 换页刷新
      currentChange(pageNum) {
        this.pageRequest.pageNum = pageNum;
        this.findPage();
      },
      sizeChange(pageSize) {
        this.pageRequest.pageNum = 1;
        this.pageRequest.pageSize = pageSize;
        this.findPage();
      },
    // 获取分页数据
      findPage: function(data) {
        let this_=this;
        if(data != null && data.start != null){
        if(data.start != null){
          this.pageRequest.pageNum = data.start;
        }
        if(data.limit != null){
          this.pageRequest.pageSize = data.limit;
        }
       }
        if (this_.filters == undefined || this_.filters == null) {
          this_.filters = {};
        }
        this_.filters.start = this.pageRequest.pageNum;
        this_.filters.limit = this.pageRequest.pageSize;
        this.utils.request.findMemMemberCustomLabelPage(this.filters, function (res) {
          if (res.data == null) {
              res.data = [];
              res.totle = 0;
          }else{
            if(res.data.rows.length>0){
              this_.checkButtonStatus(res.data.rows[0].deptType);
            }
              this_.tableList=res.data.rows;
              this_.totalSize=res.data.total;
              this_.loading=false;
          }
        });
      },
      //操作按钮显示
      checkButtonStatus(deptTypeList){
        if(this.deptType == deptTypeList){
          this.checkButton=true;
        }else{
          this.checkButton=false;
        }
      },
      //所属组织初始化
      queryDeptTree() {
        this.utils.request.getAuthorDeptTree({}, res => {
          if (res.code == "0000") {
             this.deptOption = res.data.length==0? null : res.data;
             this.filters.deptId = localStorage.getItem("deptId");
          }
        })
      },
      //类目树选中
      treeSelect: function (param) {
        this.filters.id = param.id;
        /*this.filters.name = param.name;
        this.filters.type=param.type;*/
      },
      //格式化组织初查询条件
      normalizer(node) {
        if (node.children == null || node.children.length == 0) {
          delete node.children;
        }
        return {
          id: node.id,
          label: node.deptName,
          children: node.children
        }
      },
    // 获取分页数据
      handleClose() {
        this.$refs.dataForm.resetFields();
        this.dialogVisible = false;
      },
      //查看方法
      handleLookInfo(data){
        this.dataFormLook.deptName=data.deptName;
        this.dataFormLook.labelName=data.labelName;
        this.dialogVisibleLook=true;
      },
      // 删除
      handleDeleteInfos: function(data) {
        let this_=this;
        this.$confirm("您确定要删除该标签?", "提示", {
          type: "warning",
          closeOnClickModal: false
        })
          .then(() => {
            var params = {};
            params.id = data.id;
            this_.utils.request.delMemMemberCustomLabel(params, function(res) {
            if (res.code == "0000") {
              this_.dialogVisible = false;
              this_.findPage();
              this_.$message({message: "操作成功",type: "success"});
            }
          })
        }).catch(error => {

        });
      },
      // 显示新增界面
      handleAdd: function() {
        this.dataForm={
          id:null,
          labelName:'',
          deptName:'',
        }
        this.dialogVisible = true;
        this.operation = true;
        this.dataForm.deptName=JSON.parse(this.deptMsg).deptName;
      },

      // 显示编辑界面
      handleEdit: function(params) {
        this.addDeptOperate = false;
        this.editDeptOperate = true;
        this.dialogVisible = true;
        this.operation = false;
        this.dataForm = Object.assign({}, params);
      },
      // 编辑
      submitForm: function() {
        let this_ = this;
        this.$refs.dataForm.validate(valid => {
          if (valid) {
             let params = Object.assign({}, this_.dataForm);
             params.type=0;
             this.utils.request.addMemMemberCustomLabel(params, function(res) {
              if (res.code == "0000") {
                this_.dialogVisible = false;
                this_.findPage();
                this_.$message({message: "操作成功",type: "success"});
              }else{
                this_.$message({message: "操作失败"+res.msg,type: "error"});
              }

            });
          }
        });
      },

      actionSure() {
        let this_ = this;
        this_.$refs["dataForm"].resetFields();
        this_.growthRuleShow = false;
        this_.dialogVisible = false;
      },
      // 处理表格列过滤显示
      displayFilterColumnsDialog: function() {
        this.$refs.tableColumnFilterDialog.setDialogVisible(true);
      },
      // 处理表格列过滤显示
      handleFilterColumns: function(data) {
        this.filterColumns = data.filterColumns;
        this.$refs.tableColumnFilterDialog.setDialogVisible(false);
      },
      // 处理表格列过滤显示
      initColumns: function() {
        this.columns = [
          { prop: "id", label: "ID", minWidth: 100 },
          { prop: "labelName", label: "标签名称", minWidth: 100 },
          { prop: "deptName", label: "所属组织", minWidth: 100 },
          {
            prop: "deptType",
            label: "组织层级",
            formatter: function(row, column, cellValue, index) {
              if (row.deptType == "0") {
                return "母平台";
              } else if (row.deptType == "1") {
                return "子平台";
              } else if (row.deptType == "2") {
                return "商家";
              } else if (row.deptType == "3") {
                return "店铺";
              }
            }
          },
          { prop: "createTime", label: "创建时间", minWidth: 120 },
          { prop: "markTimes", label: "标记次数", minWidth: 120 },
        ];
        var temp = [];
        $.each(this.columns, function(key, val) {
          temp.push(val);
        });
        this.filterColumns = temp;
      },
      resetForm(formName) {
        //需要校验的key
      let keys = ["startTime","endTime","labelName","deptId"]
      let boo = this.seachTableUtils.checkFromIsNull(this.filters,keys)
      if(!boo){
        return
      }
      this.filters = {
        start:1,
        limit:10,
        endTime: null,
        startTime: null,
        labelName:null,
        deptId:localStorage.getItem("deptId"),
      };
      this.findPage();
      },
    },
    mounted() {
      this.findPage();
      this.queryDeptTree();
    }
  };
</script>

<style lang='scss' scoped>
  .dialogInput {
    text-align: left;
    /deep/ .el-input {
      width: 200px;
    }
    /deep/ .el-input__inner {
      width: 200px !important;
    }
  }
  .w90{
    width: 90px;
  }
  .search-input{
  .times {
    .times-to {
      padding: 0 10px;
      height: 32px;
      line-height: 32px;
      color: #999;
      display: inline-block;
    }
    /deep/ .el-input{
      width:auto !important;
      /deep/ .el-input__inner{
        width: auto !important;
      }
    }
  }
}
/deep/ .el-form-item__error{
  left: 92px !important;
}
</style>
